package cn.core.act.rest;

import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * cs REST API
 */
@Log4j2
@RestController
@Scope("prototype")
@RequestMapping("cs/aviator")
public class CsAviatorController {

  @Resource
  private AviatorEvaluatorInstance aviatorEvaluatorInstance;

  /**
   * cs
   * http://127.0.0.1:6660/api/cs/aviator/cs
   * @return 返回
   */
  @GetMapping("cs")
  public String cs() throws Exception {
    try {
//      AviatorEvaluatorInstance aviatorEvaluatorInstance = AviatorEvaluator.getInstance();
//      aviatorEvaluatorInstance.addFunction(new AddFunc());
//      aviatorEvaluatorInstance.addFunction(new SubFunc());
//      aviatorEvaluatorInstance.addFunction(new MulFunc());
//      aviatorEvaluatorInstance.addFunction(new DivFunc());

//      let result = seq.map();
//      let param1 = add(a, b);
//      log('>>>' + param1 + '<<<');
//      let param2 = mul(param1, c);
//      seq.put(result, 'r', param2);
//      return result;

      String expStr = "let result = seq.map();\n" +
          "let param1 = add(a, b);\n" +
          "log('>>>' + param1 + '<<<');\n" +
          "let param2 = mul(param1, c);\n" +
          "seq.put(result, 'r', param2);\n" +
          "return result;";
      Expression exp = aviatorEvaluatorInstance.compile(expStr);
      LinkedHashMap<String, Object> param = new LinkedHashMap<>();
      param.put("a", "3");
      param.put("b", "3");
      param.put("c", "3");
      HashMap<String, Object> ro = (HashMap) exp.execute(param);
      System.out.println(ro.get("r"));

//      if (new BigDecimal("00.0000000000000000").stripTrailingZeros().scale() == 0) {
//        System.out.println("true");
//      } else {
//        System.out.println("false");
//      }
    } catch (ArithmeticException e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      String asd = e.getMessage();
      System.out.println();
      throw e;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
    return "";
  }

}
